package com.hrs.core.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrs.common.exception.GlobalException;
import com.hrs.common.result.CodeMsg;
import com.hrs.common.result.Result;
import com.hrs.enity.db.File;
import com.hrs.core.service.FileService;
import com.hrs.core.mapper.FileMapper;
import com.hrs.enity.vo.FileVo;
import com.hrs.util.RequestUserUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
* @author 纱雾休比酱
* @description 针对表【t_file(文件)】的数据库操作Service实现
* @createDate 2023-01-13 03:08:38
*/
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File>
    implements FileService{

    @Value("${file.path}")
    private String fileParentPath;


    @Override
    public Result<File> localUpload(MultipartFile file) {
        if (null == file) {
            return Result.error("文件为空");
        }

        String filePath = System.getProperty("user.dir") + "/file/";
        String path = "";

        java.io.File directory = new java.io.File(filePath);
        if (!directory.exists()) {
            // 目录不存在，新建
            directory.mkdirs();
        }

        String fileOldName = file.getOriginalFilename();

        String newFileName =
                UUID.randomUUID().toString().replace("-","") + fileOldName.substring(fileOldName.lastIndexOf("."));


        java.io.File fileTemp;

        fileTemp = new java.io.File(new java.io.File(filePath + newFileName).getAbsolutePath());

        //保存文件信息
        File fileEntity = new File();
        fileEntity.setFileName(newFileName);
        fileEntity.setFilePath(path + newFileName);
        fileEntity.setFileSize(file.getSize());
        fileEntity.setCreatorId(RequestUserUtil.getRequestUserId());
        this.save(fileEntity);

        try {
            file.transferTo(fileTemp);
        } catch (IOException e) {
            if (fileTemp.exists() && fileTemp.isFile()) {
                fileTemp.delete();
            }
            log.error("", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("上传失败");
        }
        return Result.success(fileEntity);
    }

    @Override
    public void localDownload(HttpServletResponse response, String path) {
        try {
            String filePath = System.getProperty("user.dir") + "/file/" + path;
            java.io.File file = new java.io.File(filePath);
            String filename = file.getName();
            FileInputStream fileInputStream = new FileInputStream(file);
            BufferedInputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            fileInputStream.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8));
            response.reset();
            response.setContentType("application/octet-stream;charset=utf-8");
            response.addHeader("content-disposition","attachment; filename=" + URLEncoder.encode(filename,"UTF-8"));
            response.setCharacterEncoding("UTF-8");
            BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();

            outputStream.close();
        } catch (Exception e) {
            if(e instanceof FileNotFoundException) {
                throw new GlobalException(new CodeMsg("文件不存在"));
            }
            e.printStackTrace();
            throw new GlobalException(new CodeMsg("图片下载失败"));
        }
    }
}




